package Util

import (
	"fmt"
	"net/http"
	"os"
	"path"
	"strings"
)

// CorsMiddleware 中间件函数，用于设置跨域请求的响应头
func CorsMiddleware(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Add("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,currentenvironment")
		w.Header().Add("Access-Control-Allow-Credentials", "true")
		w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		w.Header().Set("content-type", "application/json;charset=UTF-8")
		w.WriteHeader(http.StatusOK)
		// 如果是预检请求，直接返回
		if r.Method == http.MethodOptions {
			return
		}
		// 调用下一个处理函数
		handler.ServeHTTP(w, r)
	})
}

var docRoot = "dist"

func StaticFileServe() (fs http.Handler) {
	docRoot = path.Clean(docRoot)
	_, err := os.Stat(docRoot)
	if err != nil {
		fmt.Println(fmt.Sprintf("配置项docRoot:%s不存在或无权限，请修正", docRoot))
		os.Exit(-1)
		return
	}

	idxFile := docRoot + "/index.html"
	_, err = os.Stat(idxFile)
	if os.IsNotExist(err) {
		fmt.Println(fmt.Sprintf("配置项docRoot:%s不存在，请修正", idxFile))
		os.Exit(-1)
		return
	}

	rootFS := http.FileServer(http.Dir(docRoot))
	fs = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if w == nil || r == nil {
			fmt.Println("w or r is nil", idxFile)
			os.Exit(-1)
			return
		}
		rPath := r.URL.Path
		if !strings.HasPrefix(rPath, "/") {
			rPath = "/" + rPath
			r.URL.Path = rPath
		}

		dstFileName := path.Clean(docRoot + rPath)
		_, err = os.Stat(dstFileName)
		if os.IsNotExist(err) {
			//重定向至首页
			r.URL.Path = "/index.html"
		}
		//对js文件的Content-Type设置正确的类型
		if strings.HasSuffix(dstFileName, ".js") {
			w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
		}
		if strings.HasSuffix(dstFileName, ".css") {
			w.Header().Set("Content-Type", "text/css")
		}
		rootFS.ServeHTTP(w, r)
	})
	http.StripPrefix("/", rootFS)
	return fs
}
